package com.seraph.td.socket;

import java.io.BufferedReader;
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import weibo4andriod.org.json.JSONException;
import weibo4andriod.org.json.JSONObject;

public class UuseeRemoteServer  {
	static private UuseeRemoteServer sulf;
	private ServerSocket lSerivce;
	private Socket rSocket;
	private boolean runFlg = false;
	UuseeRemoteServerListener mListener;
	
	InputStream in = null;
	OutputStream out =null;
	
	private boolean isConnect;
	private Thread WorkThread  = new Thread(){

		@Override
		public void run() {
			// TODO Auto-generated method stub
			
			try {
				while(true){
				    rSocket = lSerivce.accept();
				    InetSocketAddress host = (InetSocketAddress) rSocket.getRemoteSocketAddress();
				    String addr = host.getAddress().getHostAddress();
				    int port = host.getPort();
				    System.out.println("NEW CONNECT HOST==="+addr+"\tPort==="+port);
					if(mListener!=null)	
						mListener.onConnect(addr, port);
				    in = rSocket.getInputStream();
					out = rSocket.getOutputStream();
				    while(true){
				    	
				    	 if(-1 ==processCMD())
				    		 break;
				    }
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	};

private int processCMD() {
	// TODO Auto-generated method stub
		int readLen  = 0;

		String head;
		String data;
		String tail;
		BufferedReader read = null;
		try{
			byte[] rBuffer = new byte[1024];
			readLen = in.read(rBuffer);
			if(readLen == -1){
				rSocket.close();
				in.close();
				out.close();
				if(mListener !=null)
					mListener.onClosed();
				return -1;
			}
			String temp = new String(rBuffer,0,readLen);
			 read = new BufferedReader(new CharArrayReader(temp.toCharArray()));
			head = read.readLine();
			if(head.equals("UUSEE_REMOVE_CMD_BEGIN")){
				data = read.readLine();
				String cmd = processJSON(data);
				if(cmd!=null){
					if(mListener !=null)
						mListener.onReceive(cmd);
					System.out.println("server---------receive--cmd="+cmd);
					tail = read.readLine();
					if(tail.equals("UUSEE_REMOVE_CMD_END")){
						//报告CLIENT 正常解析数据，接受到命令结束标志
						out.write("UUSEE_CMD_RECEIVE_OK\n".getBytes());
					}else{
						//关闭所有辅助流,报告错误。
					}
				}else{
					//关闭所有辅助流,报告错误。
				}
				
				
			}else{
				//取出本次命令的剩余字符。
			}
		}catch (IOException e) {
			// TODO: handle exception
			System.out.println("IO ERROR");
		}finally{
			try {
				if(read!=null)
					read.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return 0;
}
private String processJSON(String json){
	String result = null;
	try {
		JSONObject obj = new JSONObject(json);
		result = obj.getString("cmd");
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
		return result;
	}
	
	return result;
}
	static UuseeRemoteServer open(int port,UuseeRemoteServerListener listener){
		if(sulf != null){
			sulf.close();
		}
		sulf = new UuseeRemoteServer();
		sulf.mListener = listener;
		try {
			sulf.lSerivce = new ServerSocket(port);
			sulf.startWorkThread();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("open port error");
		}
		
		return sulf;
	}
	
	private  void startWorkThread() {
		// TODO Auto-generated method stub
		runFlg = true;
		WorkThread.start();
		
	}
	public void close() {
		// TODO Auto-generated method stub
		
	}

	private UuseeRemoteServer(){
		
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		UuseeRemoteServer.open(5852, null);
	}

}
